package io.webapi;

import io.HttpTools;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BingImage {
    static String getBingHome() throws IOException {
        String url = "https://www.bing.com";
        return HttpTools.doGetString(url);
    }

    static String parseImageUrl(String html) {
        Pattern imageUrlPattern = Pattern.compile("content=\"(https://www\\.bing\\.com/th.+?\\.jpg)");
        Matcher matcher = imageUrlPattern.matcher(html);
        if (matcher.find()) {
            String ret = matcher.group(1);
            return ret;
        }
        return null;
    }

    static void saveImage(String imageUrl) throws IOException {
        String filePath = "D:\\bing.jpg";
        try (InputStream is = HttpTools.doGet(imageUrl);
             FileOutputStream fos = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        }
        Runtime.getRuntime().exec("cmd /c start " + filePath);
    }

    public static void main(String[] args) throws IOException {
        String html = getBingHome();
        System.out.println("bing html：");
        System.out.println(html);

        String imageUrl = parseImageUrl(html);
        System.out.println("bing image url：" + imageUrl);
//
        saveImage(imageUrl);
    }
}
